﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace FitAutomation.FitProcess
{
	//[Serializable]
	public class XmlPackageItem
	{
		public XmlPackageItem()
		{
			
		}

		public XmlPackageItem(object obj)
		{
			Object = obj;
			Type = obj.GetType();
		}

		public Type Type;
		public object Object;
	}

	[XmlRoot("Package")]
	public class XmlPackage : IXmlSerializable
	{
		public XmlPackage()
		{
			Objects = new List<object>();
		}

		public XmlPackage(IEnumerable<object> objects)
		{
			Objects = new List<object>(objects);
		}

		public XmlPackage(object obj)
		{
			Objects = new List<object>(new[]{obj});
		}

		public readonly List<object> Objects;

		public XmlSchema GetSchema()
		{
			return null;
		}

		public void ReadXml(XmlReader reader)
		{
			Objects.Clear();

			reader.ReadStartElement("Package");

			while (reader.Name == "item")
			{
				var typeName = reader.GetAttribute("ClrType");

				reader.ReadStartElement("item");
				
				var base64 = reader.ReadString();
				var type = Type.GetType(typeName, true);
				var buf = Convert.FromBase64String(base64);
				var item = Serializer.Deserialize(buf, type);
				Objects.Add(item);

				reader.ReadEndElement();
			}

			reader.ReadEndElement();
		}

		public void WriteXml(XmlWriter writer)
		{
			foreach (var item in Objects)
			{
				writer.WriteStartElement("item");
				var type = item.GetType();
				writer.WriteAttributeString("ClrType", type.AssemblyQualifiedName);
				byte[] buf = Serializer.Serialize(item);
				writer.WriteString(Convert.ToBase64String(buf));
				writer.WriteEndElement();
			}
		}

	}
}